import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchCount = createAsyncThunk('counter/fetchCount', async (amount: number) => {
  return new Promise<number>((resolve) => setTimeout(() => resolve(amount), 1000));
});

interface CounterState {
  value: number;
  loading: boolean;
}

const initialState: CounterState = {
  value: 0,
  loading: false,
};

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchCount.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchCount.fulfilled, (state, action) => {
        state.value += action.payload;
        state.loading = false;
      })
      .addCase(fetchCount.rejected, (state) => {
        state.loading = false;
      });
  },
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
